package ui.swing.font;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;

import javax.swing.JPanel;

import ui.swing.Console;

public class FontPanel extends JPanel{

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		
		Graphics2D g2 = (Graphics2D)g;
		
		String message = "operation!";
		
		Font f = new Font("Sans Serif", Font.BOLD, 72);
		g2.setFont(f);
		
		// measure the size of the message
		FontRenderContext context = g2.getFontRenderContext();
		Rectangle2D bounds = f.getStringBounds(message, context);
		// bounds.getX() - 0; bounds.getY() - ascent; bounds.getWidth() - 长度; bounds.getHeight() 高度
		
		// set (x,y) = top left corner of text
		
		double x = (getWidth() - bounds.getWidth()) / 2;
		double y = (getHeight() - bounds.getWidth()) / 2;
		
		// add ascent to y to reach the baseline
		double ascent = -bounds.getY();
		double baseY = y + ascent;

		System.out.println(bounds.getX());
		System.out.println(ascent);
		
		// draw the message
		g2.drawString(message, (int)x, (int)baseY);
		

		g2.setPaint(Color.GRAY);
		// draw the baseline
		g2.draw(new Line2D.Double(x, baseY, x + bounds.getWidth(), baseY));
		// draw the enclosing rectangle
		Rectangle2D rect = new Rectangle2D.Double(x,y,bounds.getWidth(),bounds.getHeight());
		g2.draw(rect);

		FontMetrics fm = g2.getFontMetrics();
		Line2D topline = new Line2D.Double(x, baseY - fm.getAscent(), x + bounds.getWidth(),  baseY - fm.getAscent());
		Line2D buttomline = new Line2D.Double(x, baseY + fm.getDescent(), x + bounds.getWidth(),  baseY + fm.getDescent());

		g2.setPaint(Color.RED);
		g2.draw(topline);
		
		g2.setPaint(Color.BLUE);
		g2.draw(buttomline);
	}
	
	public static void main(String[] args) {
		Console.run(new FontPanel(), 500, 500);
	}
}
